package com.jz.yanshe.ui.fragment;

import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.media.ThumbnailUtils;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aspsine.swipetoloadlayout.OnLoadMoreListener;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.aspsine.swipetoloadlayout.SwipeToLoadLayout;

import com.jz.yanshe.ui.widget.CustomPopWindow;
import com.jz.jd.rest.business.RestProxy;
import com.jz.jd.rest.response.Goods;
import com.jz.jd.rest.response.RedResponse;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import cn.jzvd.JZVideoPlayer;
import cn.jzvd.JZVideoPlayerStandard;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import com.jz.yanshe.base.BaseFragment;
import com.jz.yanshe.util.ImageLoaderHelper;
import com.jz.yanshe.R;
import com.jz.yanshe.ui.MatchActivity;
import com.jz.yanshe.util.PreferencesHelper;

/**
 * Created by Administrator on 2018/2/26.
 */

public class RedFragment extends BaseFragment implements OnRefreshListener, OnLoadMoreListener {

    @BindView(R.id.swipe_target)
    RecyclerView recyclerView;
    @BindView(R.id.swipeToLoadLayout)
    SwipeToLoadLayout swipeToLoadLayout;
    int page = 1;

//    Handler mHandler;

    MyAdapter myAdapter = new MyAdapter();

    private CustomPopWindow mListPopWindow;

    List<RedResponse.Red> list = new ArrayList<>();
//    List<ImageView> listImage = new ArrayList<>();

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_red;
    }

    private static RedFragment redFragment;


    @Override
    protected void initView() {
        recyclerView.setAdapter(myAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        swipeToLoadLayout.setLoadMoreEnabled(false);
        swipeToLoadLayout.setRefreshEnabled(false);
    }

    public static RedFragment newInstance() {
        if (redFragment == null) {
            redFragment = new RedFragment();
            return redFragment;
        } else {
            return redFragment;
        }
    }

    @Override
    protected void initData() {
        getRedGoods();
//        mHandler = new Handler() {
//            @Override
//            public void handleMessage(Message msg) {
//                listImage.get(msg.arg1).setScaleType(ImageView.ScaleType.CENTER_CROP);
//                listImage.get(msg.arg1).setImageBitmap((Bitmap) msg.getData().getParcelable("obj"));
//            }
//        };
    }

    @Override
    public void onLoadMore() {

    }

    @Override
    public void onRefresh() {

    }


    class MyAdapter extends RecyclerView.Adapter<MyAdapter.Holder> {


        @Override
        public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
            Holder holder = new Holder(getLayoutInflater().inflate(R.layout.item_red, parent, false));
            return holder;
        }

        @Override
        public void onBindViewHolder(final Holder holder, final int position) {
            HorizantalAdapter horizantalAdapter = new HorizantalAdapter(position);
            holder.horizantalRecyclerView.setAdapter(horizantalAdapter);
            LinearLayoutManager manager = new LinearLayoutManager(getActivity());
            manager.setOrientation(LinearLayoutManager.HORIZONTAL);
            holder.horizantalRecyclerView.setLayoutManager(manager);
//            listImage.add(holder.videoplayer.thumbImageView);
            if (list.get(position).video_url != null && !list.get(position).video_url.equals("")) {
                holder.videoplayer.setUp(list.get(position).video_url, JZVideoPlayer.SCREEN_WINDOW_NORMAL);
//                Glide.with(getActivity()).load(Uri.fromFile(new File(list.get(position).video_url))).into(holder.videoplayer.thumbImageView);
//                createVideoThumbnail(list.get(position).video_url, 100, 100, position);
//                holder.videoplayer.thumbImageView.setImageBitmap();
            } else {
                holder.videoplayer.setVisibility(View.INVISIBLE);
            }
            holder.videoplayer.releaseAllVideos();
            holder.videoplayer.thumbImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            ImageLoaderHelper.getInstance().GlideImageLoader(getActivity(), list.get(position).video_img_url, holder.videoplayer.thumbImageView);
            holder.videoplayer.batteryLevel.setVisibility(View.INVISIBLE);
            holder.videoplayer.backButton.setVisibility(View.INVISIBLE);
            double price = 0;
            int num = 0;
            for (int i = 0; i < list.get(position).stylesList.size(); i++) {
                if (list.get(position).stylesList.get(i).select) {
                    price = price + Double.valueOf(list.get(position).stylesList.get(i).goods_price);
                    num++;
                }
            }

            holder.btn_share.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showPopListView(holder.itemView);
                }
            });
            holder.tv_price.setText("共" + num + "件商品 合计：¥" + String.format("%.2f", Double.valueOf(price)));

            holder.tv1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(holder.horizantalRecyclerView.getVisibility() == View.VISIBLE){
                        holder.horizantalRecyclerView.setVisibility(View.INVISIBLE);
                    }else{
                        holder.horizantalRecyclerView.setVisibility(View.VISIBLE);
                    }
                }
            });

            holder.btn_buy.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    List<Goods> goodsList = new ArrayList<>();
                    for (int i = 0; i < list.get(position).stylesList.size(); i++) {
                        if (list.get(position).stylesList.get(i).select) {
                            goodsList.add(list.get(position).stylesList.get(i));
                        }
                    }
                    if (goodsList.size() == 0) {
                        Toast.makeText(getActivity(), "请选择购买商品", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("list", (Serializable) goodsList);
                    startActivity(MatchActivity.class, bundle);
                }
            });
        }


        @Override
        public int getItemCount() {
            return list.size();
        }

        class Holder extends RecyclerView.ViewHolder {
            TextView tv_price, btn_pay,  tv_benjin, tv_yongjin, tv_starttime;
            JZVideoPlayerStandard videoplayer;
            RecyclerView horizantalRecyclerView;
            LinearLayout btn_share,tv1,btn_buy;

            public Holder(View itemView) {
                super(itemView);
                horizantalRecyclerView = itemView.findViewById(R.id.recyclerView);
                videoplayer = itemView.findViewById(R.id.videoplayer);
                tv_price = itemView.findViewById(R.id.tv_price);
                btn_pay = itemView.findViewById(R.id.btn_pay);
                btn_share = itemView.findViewById(R.id.btn_share);
                tv1 = itemView.findViewById(R.id.tv1);
                btn_buy = itemView.findViewById(R.id.btn_buy);
//                tv_benjin = itemView.findViewById(R.id.tv_benjin);
//                tv_yongjin = itemView.findViewById(R.id.tv_yongjin);
//                tv_starttime = itemView.findViewById(R.id.tv_starttime);
            }
        }
    }

    class HorizantalAdapter extends RecyclerView.Adapter<HorizantalAdapter.Holder> {

        int positionParent;

        public HorizantalAdapter(int position) {
            this.positionParent = position;
        }

        @Override
        public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
            Holder holder = new Holder(getLayoutInflater().inflate(R.layout.item_red_goods, parent, false));
            return holder;
        }

        @Override
        public void onBindViewHolder(final Holder holder, final int position) {

            if (list.get(positionParent).stylesList.get(position).select) {
                holder.img_goods.setBackgroundResource(R.color.commonRed);
            } else {
                holder.img_goods.setBackgroundResource(R.color.white);
            }
            holder.tv_goods_name.setText(list.get(positionParent).stylesList.get(position).goods_name);
            ImageLoaderHelper.getInstance().GlideImageLoader(getActivity(), list.get(positionParent).stylesList.get(position).goods_icon, holder.img_goods);
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (list.get(positionParent).stylesList.get(position).select) {
                        list.get(positionParent).stylesList.get(position).select = false;
                    } else {
                        list.get(positionParent).stylesList.get(position).select = true;
                    }
                    notifyDataSetChanged();
                    myAdapter.notifyDataSetChanged();
                }
            });
        }

        @Override
        public int getItemCount() {
            return list.get(positionParent).stylesList.size();
        }

        class Holder extends RecyclerView.ViewHolder {
            TextView tv_goods_name;
            ImageView img_goods;

            public Holder(View itemView) {
                super(itemView);
                tv_goods_name = itemView.findViewById(R.id.tv_goods_name);
                img_goods = itemView.findViewById(R.id.img_goods);
//                tv_benjin = itemView.findViewById(R.id.tv_benjin);
//                tv_yongjin = itemView.findViewById(R.id.tv_yongjin);
//                tv_starttime = itemView.findViewById(R.id.tv_starttime);
            }
        }
    }


    private void getRedGoods() {
        RestProxy.getInstance().getRedGoods(PreferencesHelper.getInstance().getString(getActivity(), "token"), new Observer<RedResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(RedResponse redResponse) {
                list.clear();
                list.addAll(redResponse.listM);
                myAdapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {

            }
        });
    }

//    @Override
//    public void onHiddenChanged(boolean hidden) {
//        super.onHiddenChanged(hidden);
//        if (hidden) {
//            System.out.println("不可见");
//            myAdapter.notifyDataSetChanged();
//        } else {
//            System.out.println("当前可见");
//        }
//    }
//
//    @Override
//    public void setUserVisibleHint(boolean isVisibleToUser) {
//        super.setUserVisibleHint(isVisibleToUser);
//        if (getUserVisibleHint()) {
//            System.out.println("a");
//        } else {
//            System.out.println("b");
//            myAdapter.notifyDataSetChanged();
//        }
//    }

//    public void clearVideo(){
//        myAdapter.
//    }


//    private void createVideoThumbnail(final String url, final int width, final int height, final int position) {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                Bitmap bitmap = null;
//                MediaMetadataRetriever retriever = new MediaMetadataRetriever();
//                int kind = MediaStore.Video.Thumbnails.MINI_KIND;
//                try {
//                    if (Build.VERSION.SDK_INT >= 14) {
//                        retriever.setDataSource(url, new HashMap<String, String>());
//                    } else {
//                        retriever.setDataSource(url);
//                    }
//                    bitmap = retriever.getFrameAtTime();
//                } catch (IllegalArgumentException ex) {
//                    // Assume this is a corrupt video file
//                } catch (RuntimeException ex) {
//                    // Assume this is a corrupt video file.
//                } finally {
//                    try {
//                        retriever.release();
//                    } catch (RuntimeException ex) {
//                        // Ignore failures while cleaning up.
//                    }
//                }
//                if (kind == MediaStore.Images.Thumbnails.MICRO_KIND && bitmap != null) {
//                    bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
//                            ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
//                }
//                Message msg = new Message();
//                Bundle bundle = new Bundle();
//                bundle.putParcelable("obj", bitmap);
//                msg.setData(bundle);
//                msg.arg1 = position;
//                mHandler.sendMessage(msg);
////                bitmap;
//            }
//        }).start();
//
//    }

    //    public static Bitmap createVideoThumbnail(String filePath,int kind){
//        Bitmap bitmap = null;
//        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
//        try {
//            if (filePath.startsWith("http://")
//                    || filePath.startsWith("https://")
//                    || filePath.startsWith("widevine://")) {
//                retriever.setDataSource(filePath,new Hashtable<S['tring,String>());
//            }else {
//                retriever.setDataSource(filePath);
//            }
//            bitmap =retriever.getFrameAtTime(-1);
//        } catch (IllegalArgumentException ex) {
//            // Assume this is a corrupt video file
//            ex.printStackTrace();
//        } catch (RuntimeException ex) {
//            // Assume this is a corrupt video file.
//            ex.printStackTrace();
//        } finally {
//            try {
//                retriever.release();
//            } catch (RuntimeException ex) {
//                // Ignore failures while cleaning up.
//                ex.printStackTrace();
//            }
//        }
//
//        if (bitmap==null)return null;
//
//        if (kind== MediaStore.Images.Thumbnails.MINI_KIND) {
//            // Scale down the bitmap if it's too large.
//            int width= bitmap.getWidth();
//            int height= bitmap.getHeight();
//            int max =Math.max(width, height);
//            if(max >512) {
//                float scale=512f / max;
//                int w =Math.round(scale * width);
//                int h =Math.round(scale * height);
//                bitmap = Bitmap.createScaledBitmap(bitmap,w, h, true);
//            }
//        } else if (kind== MediaStore.Images.Thumbnails.MICRO_KIND) {
//            bitmap = ThumbnailUtils.extractThumbnail(bitmap,
//                    96,
//                    96,
//                    ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
//        }
//        return bitmap;
//    }
    private void showPopListView(View parent) {
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.popwindow_share, null);
        TextView btn_cancel = contentView.findViewById(R.id.btn_cancel);
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mListPopWindow.dissmiss();
            }
        });

        //处理popWindow 显示内容
        //创建并显示popWindow
        mListPopWindow = new CustomPopWindow.PopupWindowBuilder(getActivity())
                .setView(contentView)
                .size(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) // 显示大小
                .create()
                .showAtLocation(parent, Gravity.BOTTOM, 0, 0);
    }

}
